package com.iterative.system.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.iterative.common.persistence.HibernateDao;
import com.iterative.common.service.BaseService;
import com.iterative.common.util.DateUtils;
import com.iterative.common.util.security.Digests;
import com.iterative.common.util.security.Encodes;
import com.iterative.system.dao.UserDao;
import com.iterative.system.entity.User;


@Service
@Transactional(readOnly = true)
public class UserService extends BaseService<User, Long> {
    //加密信息
    public static final String HASH_ALGORITHM = "SHA-1";
    public static final int HASH_INTERATIONS = 1024;
    private static final int SALT_SIZE = 8; //盐长度
    @Autowired
    private UserDao userDao;

    @Override
    public HibernateDao<User, Long> getEntityDao() {
        return userDao;
    }

    public User getUser(String loginName) {
        return userDao.findUniqueBy("loginName", loginName);
    }
    @Transactional(readOnly=false)
	public void updateUserLogin(User user) {
		user.setLoginCount((user.getLoginCount()==null?0:user.getLoginCount())+1);
		user.setPreviousVisit(user.getLastVisit());
		user.setLastVisit(DateUtils.getSysTimestamp());
		update(user);
	}

	@Transactional(readOnly=false)
	public void save(User user) {
		entryptPassword(user);
		user.setCreateDate(DateUtils.getSysTimestamp());
		userDao.save(user);
	}
	
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(user.getPlainPassword().getBytes(),salt, HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}
	
	
}
